﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BLL;

namespace WebUI.Pages
{
    public partial class mgrUsers : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            UserController usrController = new UserController();
            TeamController tmController = new TeamController();

            int idUsuario = usrController.GetUserID(User.Identity.Name);
            int idTime = usrController.GetUserTeamID(idUsuario);

            if (idTime != 9)
            {
                Response.Redirect("../Pages/403.aspx");
            }
            if (!this.IsPostBack)
            {
                ddlGestor.DataSource = usrController.GetTeamUsers(9);
                ddlGestor.DataValueField = "idUsuario";
                ddlGestor.DataTextField = "Nome";
                ddlGestor.DataBind();

                ddlTime.DataSource = tmController.GetTeams();
                ddlTime.DataValueField = "idTime";
                ddlTime.DataTextField = "DescTime";
                ddlTime.DataBind();

                rpUsuarios.DataSource = usrController.GetTeamUsers(0);
                rpUsuarios.DataBind();

            }
        }

        protected void cmdNovo_Click(object sender, EventArgs e)
        {
            try
            {
                UserController usrController = new UserController();
                TeamController tmController = new TeamController();

                string username = txtNome.Text;
                string Login = txtLogin.Text;
                int idTime = Convert.ToInt32(ddlTime.SelectedValue);
                int idGestor = Convert.ToInt32(ddlGestor.SelectedValue);

                usrController.CreateUser(username, idTime, idGestor, Login);
            }
            catch (Exception ex)
            {
                lblMsg.Text = "Erro ao criar usuário. " + ex.Data;
            }
            finally
            {
                txtLogin.Text = "";
                txtNome.Text = "";
                ddlGestor.SelectedIndex = 0;
                ddlTime.SelectedIndex = 0;
                Response.Redirect("../Pages/mgrUsers.aspx");
            }
        }

        protected void cmdUpdate_Click(object sender, EventArgs e)
        {
            UserController usrController = new UserController();
            
            rpUsuarios.DataSource = usrController.GetTeamUsers(0);
            rpUsuarios.DataBind();
        }

        protected void rpUsuarios_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            if (e.CommandName == "cmdEdit")
            {
                Response.Redirect("../Pages/editUser.aspx?id=" + e.CommandArgument.ToString());
            }
        }
    }
}